<?php
namespace app\api\controller\service;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Loader;


/**
 * 首页接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['refundReason','complaintReason','refundInfo','complaintInfo'];
    protected $noNeedRight = ['*'];

    public function settle()
    {
        $user = $this->auth->getUserinfo();
        $post = input('get.','','trim,strip_tags,htmlspecialchars,xss_clean');
        $data = [];
        try{
            $data['settle'] = \app\api\model\service\Order::settle($post);
            $data['money'] = \app\api\model\service\User::getMoney($user['id']);
            $data['userInfo'] = \app\api\model\service\UserInfo::where(['user_id'=>$user['id']])->field('is_plus,discount')->find();
            $data['skillInfo'] = isset($post['skill_id'])?\app\api\model\service\Skill::getOrderSkill($post['skill_id']):'';
            $data['timeInfo'] = isset($post['skill_id'])?\app\api\model\service\SkillTime::getSettleTime($post['skill_id']):\app\api\model\service\Shop::getShopTime();
        } catch (Exception $e) {
            $this->error('下单结算失败',$e->getMessage());
        }
        $this->success('信息返回成功',$data);
    }

    /**
     * 计算车费
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function travelPrice()
    {
        $get = input('get.','','trim,strip_tags,htmlspecialchars,xss_clean');
        $goodsConfig = \app\api\model\service\Goods::where(['id'=>$get['goods_id']])->value('is_travel');
        !$goodsConfig && $this->error('当前项目未开启出行费用配置');
        $timeInfo = \app\api\model\service\SkillTime::where(['id'=>$get['time_id'],'state'=>0])->field('id,starttime')->find();
        $hour = date("H",$timeInfo['starttime']);
        $cityConfig = \app\api\model\service\CityConfig::where(['city'=>$get['city']])->find();
        if($get['traveltype'] == 2)
        {

            ($hour>=$cityConfig['bus_end'] || $hour<$cityConfig['bus_start']) && $this->error('当前城市'.$cityConfig['bus_start'].'点-'.$cityConfig['bus_end'].'点可选择公交地铁出行方式');
        }
        $re = '';
        try{
            $re = \app\api\model\service\CityConfig::settleTravelPrice($get);
            $re['skillInfo'] = \app\api\model\service\Skill::checkAcceptState($get['skill_id'],$get['goods_id']);
            $re['cityConfig'] = $cityConfig;
        } catch (Exception $e) {
            $this->error('计算出行费用失败',$e->getMessage());
        }
        $this->success('出行费用返回成功',$re);
    }

    /**
     * 创建订单
     * @return void
     */
    public function createOrder()
    {
        $uid = $this->auth->id;
        $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
        $validate = Loader::validate('service.Order');
        if(!$validate->scene('add')->check($post)){
            $this->error($validate->getError());
        }
        $re = '';
        Db::startTrans();
        try{
            $post['user_id'] = $uid;
            $re = \app\api\model\service\Order::createOrder($post);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付信息返回成功',$re);
    }

    public function pay()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $paytype = input('paytype/d','');
        $re = '';
        Db::startTrans();
        try{
            $re = \app\api\model\service\Order::pay(['id'=>$id,'user_id'=>$uid,'paytype'=>$paytype]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付信息返回成功',$re);
    }

    /**
     * 订单补差价
     * @return void
     */
    public function premiumOrder()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $price = sprintf("%.2f",input('price',''));
        $price<=0 && $this->error('差价金额异常,无法支付');
        $paytype = input('paytype/d',0);
        $orderExist = \app\api\model\service\Order::where(['id'=>$id,'user_id'=>$uid,'status'=>['in',[1,2,3,4,5]]])->value('id');
        !$orderExist && $this->error('当前订单无法补差价,请联系管理员');
        $re = '';
        Db::startTrans();
        try{
            $re = \app\api\model\service\PremiumOrder::createOrder(['order_id'=>$id,'payprice'=>$price,'user_id'=>$uid,'paytype'=>$paytype]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('支付拉起失败',$e->getMessage());
        }
        $this->success('支付信息返回成功',$re);
    }


    /**
     * 附加项目创建订单
     * @return void
     */
    public function addOrder()
    {
        $uid = $this->auth->id;
        $post = input('get.','','trim,strip_tags');
        $re = '';
        Db::startTrans();
        try{
            $re = \app\api\model\service\AddOrder::createOrder(['order_id'=>$post['id'],'add_ids'=>$post['add_ids'],'user_id'=>$uid,'paytype'=>$post['paytype']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('支付拉起失败',$e->getMessage());
        }
        $this->success('支付信息返回成功',$re);
    }

    /**
     * 用户订单列表
     * @return void
     */
    public function userOrderList()
    {
        $uid = $this->auth->id;
        $get = input('get.','','trim,strip_tags');
        $get['user_id'] = $uid;
        $re = [];
        try{
            $re = \app\api\model\service\Order::getOrderList($get);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('信息返回成功',$re);
    }

    /**
     * 商户端订单列表
     * @return void
     */
    public function shopOrderList()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,category_ids,city')->find();
        $get = input('get.','','trim,strip_tags');
        
        if(!isset($get['is_pool']))
        {
            $get['shop_id'] = $shop['id'];
        }else{
            $get['city'] = $shop['city'];
            $get['is_pool'] = 1;
            $get['category_ids'] = $shop['category_ids'];
        }
        $re = [];
        // return json_encode($get);
        try{
            $re = \app\api\model\service\Order::getOrderList($get);
            // return json_encode($re);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('信息返回成功',$re);
    }

    /**
     * 服务者订单列表
     * @return void
     */
    public function skillOrderList()
    {
        $uid = $this->auth->id;
        // $uid=36; 
        $skill = \app\api\model\service\Skill::where(['user_id'=>$uid])->field('id,goods_ids,city')->find();
        !$skill && $this->error('非服务者无法访问');
        $get = input('get.','','trim,strip_tags');
        if(!isset($get['is_pool']))
        {
            $get['skill_id'] = $skill['id'];
        }else{
            $get['city'] = $skill['city'];
            $get['skill_goods_ids'] = $skill['goods_ids'];
        }
        $re = [];
        try{
            $re = \app\api\model\service\Order::getOrderList($get);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('信息返回成功',$re);
    }




    /**
     * 订单详情
     * @return void
     */
    public function orderInfo()
    {
        $id = input('id/d','');
        $order = \app\api\model\service\Order::getOrderInfo($id);
        $this->success('信息返回成功',$order);
    }


    /**
     * 申请退款
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function refundOrder()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');

        $refundOrder = \app\api\model\service\RefundOrder::where(['user_id'=>$uid,'order_id'=>$id])->order('id desc')->find();
        $type = input('type','');
        if($type == 'refund')
        {
            $post = input('post.','','trim,strip_tags');
            $post['user_id'] = $uid;
            try{
                \app\api\model\service\RefundOrder::applyRefund($post);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('已申请,等待管理员审核');
        }
        $this->success('信息返回成功',$refundOrder);
    }


    public function refundReason()
    {
        $list = \app\api\model\service\RefundReason::where(['state'=>1])->field('id,name')->select();
        $this->success('信息返回成功',$list);
    }


    public function complaintReason()
    {
        $list = \app\api\model\service\ComplaintReason::where(['state'=>1])->field('id,name')->select();
        $this->success('信息返回成功',$list);
    }


    /**
     * 订单投诉
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function complaint()
    {
        $post = input('post.','','trim,strip_tags');
        $uid = $this->auth->id;
        $order = \app\api\model\service\Order::where(['user_id'=>$uid,'id'=>$post['order_id']])->field('id,user_id,is_complaint')->find();
        (!$order && $order['is_complaint'] == 1)&& $this->error('当前订单无法投诉');
        $post['user_id'] = $uid;
        try{
            \app\api\model\service\Complaint::create($post);
            \app\api\model\service\OrderLog::create(['order_id'=>$order['id'],'user_id'=>$order['user_id'],'type'=>11,'content'=>'订单已投诉']);
            \app\api\model\service\Order::where(['id'=>$post['order_id']])->update(['is_complaint'=>1]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('投诉已发送给管理员,等待管理员审核');
    }

    public function shopAccept()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,accept_nums')->find();
        $id = input('id/d','');
        $starttime = \app\api\model\service\Order::where(['id'=>$id,'status'=>1])->value('starttime');
        $orderCount = \app\api\model\service\Order::getTotalAccept(['shop_id'=>$shop['id'],'starttime'=>$starttime]);
        $orderCount>=$shop['accept_nums'] && $this->error('订单接取已达到上限',[],2);
        Db::startTrans();
        $order = \app\api\model\service\Order::where(['id'=>$id,'status'=>1])->lock(true)->find();
        $order['shop_id'] = $shop['id'];
        try{
            \app\api\model\service\Order::shopAccept($order);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('订单接取失败',$e->getMessage());
        }
        $this->success('订单已接取');
    }


    /**
     * 服务者接取订单
     * @return void
     */
    public function skillAccept()
    {
        $uid = $this->auth->id;
        $skill = \app\api\model\service\Skill::where(['user_id'=>$uid])->field('id,accept_nums,shop_id')->find();
        $id = input('id/d','');
        $starttime = \app\api\model\service\Order::where(['id'=>$id,'status'=>1])->value('starttime');
        if($skill['shop_id'])
        {
            $shop = \app\api\model\service\Shop::where(['id'=>$skill['shop_id']])->field('id,accept_nums')->find();
            $orderCount = \app\api\model\service\Order::getTotalAccept(['shop_id'=>$skill['shop_id'],'starttime'=>$starttime]);
            $orderCount>=$shop['accept_nums'] && $this->error('商户订单接取已达到上限',[],2);
        }else{
            $orderCount = \app\api\model\service\Order::getTotalAccept(['skill_id'=>$skill['id'],'starttime'=>$starttime]);
            $orderCount>=$skill['accept_nums'] && $this->error('服务者订单接取已达到上限',[],2);
        }

        Db::startTrans();
        $order = \app\api\model\service\Order::where(['id'=>$id,'status'=>1])->lock(true)->find();
        try{
            \app\api\model\service\Order::accept(['id'=>$order['id'],'skill_id'=>$skill['id'],'shop_id'=>$skill['shop_id']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('订单接取失败',$e->getMessage());
        }
        $this->success('订单已接取');
    }


    public function skillGo()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        try{
            \app\api\model\service\Order::go(['id'=>$id,'user_id'=>$uid]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('服务人员已出发');
    }

    public function skillReach()
    {
        $uid = $this->auth->id;
        $id = input('id/d','');
        $reachImages = input('reach_images','','trim,strip_tags');
        try{
            \app\api\model\service\Order::reach(['id'=>$id,'user_id'=>$uid,'reach_images'=>$reachImages]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('服务人员已到达');
    }

    public function skillStart()
    {
        $id = input('id/d','');
        try{
            \app\api\model\service\Order::skillStart(['id'=>$id]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('服务人员已开始服务');
    }


    public function skillFinish()
    {
        $uid = $this->auth->id;
        $skillId = \app\api\model\service\Skill::where(['user_id'=>$uid])->value('id');
        $get = input('get.','','trim,strip_tags');
        $get['skill_id'] = $skillId;
        Db::startTrans();
        $order = \app\api\model\service\Order::where(['id'=>$get['id']])->lock(true)->find();
        try{
            $res = \app\api\model\service\Order::skillFinish($get);
            // return json($res);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('订单已确认完成');
    }

    public function checkOrder()
    {
        $uid = $this->auth->id;
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $checkName = input('check_name','','trim,strip_tags');
        Db::startTrans();
        $order = \app\api\model\service\Order::where(['check_name'=>$checkName,'shop_id'=>$shopId,'status'=>2])->lock(true)->find();
        try{
            \app\api\model\service\Order::checkOrder($order);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('核销成功');
    }


    public function skillSettleOrder()
    {
        $uid = $this->auth->id;
        $skill = \app\api\model\service\Skill::where(['user_id'=>$uid])->field('id,shop_id')->find();
        $get = input('get.','','trim,strip_tags');
        $get['user_id'] = $uid;
        $get['skill_id'] = $skill['id'];
        if($get['types'] == 1)
        {
            $get['shop_id'] = $skill['shop_id'];
        }
        $get['type'] = 0;
        $re = '';
        try{
            $re = \app\api\model\service\Order::searchSettleOrder($get);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('信息返回成功',$re);
    }

    public function shopSettleOrder()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id')->find();
        $get = input('get.','','trim,strip_tags');
        $get['user_id'] = $uid;
        $get['shop_id'] = $shop['id'];
        $get['type'] = 1;
        $re = '';
        try{
            $re = \app\api\model\service\Order::searchSettleOrder($get);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('信息返回成功',$re);
    }

    public function priceInfo()
    {
        $id = input('id/d','');
        $order = \app\api\model\service\Order::where(['id'=>$id])->field('id,skill_id,shop_id,price,travel_price,sumprice,goods_total_price,coupon_price,premium_price,add_price,payprice,act_travel_price,refund_price,settle_price')->find();
        $order['skillPrice'] = $order['skill_id']?\app\api\model\service\Rebate::where(['order_id'=>$id,'type'=>0,'rebatetype'=>['<>',2]])->value('num'):0;
        $order['shopPrice'] = $order['shop_id']?\app\api\model\service\Rebate::where(['order_id'=>$id,'type'=>1,'rebatetype'=>['<>',2]])->value('num'):0;
        $this->success('信息返回成功',$order);
    }


    public function refundInfo()
    {
        $id = input('order_id','');
        $refundOrder = \app\api\model\service\RefundOrder::where('order_id',$id)->order('id desc')->find();
        if($refundOrder){
            $refundOrder['images'] = $refundOrder['images']?explode(',',$refundOrder['images']):'';
        }
        $this->success('信息返回成功',$refundOrder);
    }

    public function cancelRefund()
    {
        $id = input('order_id','');
        $refundOrder = \app\api\model\service\RefundOrder::where(['order_id'=>$id,'state'=>0])->find();
        !$refundOrder && $this->error('无法取消申请,请联系管理员');
        try{
            \app\api\model\service\RefundOrder::cancelRefundOrder($refundOrder);
            $this->success('申请退款已取消');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    public function complaintInfo()
    {
        $id = input('order_id','');
        $complaint = \app\api\model\service\Complaint::where('order_id',$id)->find();
        if($complaint)
        {
            $complaint['images'] = $complaint['images']?explode(',',$complaint['images']):'';
        }
        $this->success('信息返回成功',$complaint);
    }





}
